/*
 * Copyright (C) 2010-2013 The SINA WEIBO Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sina.weibo.sdk.demo.openapi;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.demo.AccessTokenKeeper;
import com.sina.weibo.sdk.demo.R;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.UserInfoAPI;

/**
 * 该类主要演示了如何使用 {@link UserInfoAPI} 来获取用户信息。
 * 
 * @author 郑成武
 * @since 2013-12-13
 */
public class WBUserInfoAPIActivity extends Activity {
    /** 显示 用户信息*/
    private TextView mUserInfoView;
    /** 获取用户信息按钮 */
    private Button mUserInfoButton;
    /** 当前 用户信息 */
    Oauth2AccessToken mAccessToken;
    /** 回调 */
    private UserInfoRequestListener mRequestListener = new UserInfoRequestListener();
    
    /**
     * @see {@link Activity#onCreate}
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_open_api_userinfo);
        mUserInfoView = (TextView) findViewById(R.id.user_info);
        mUserInfoButton = (Button) findViewById(R.id.user_button);
        
        // 获取当前已保存过的 Token
        mAccessToken = AccessTokenKeeper.readAccessToken(this);
        if (mAccessToken != null && mAccessToken.isSessionValid()) {
            String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new java.util.Date(mAccessToken.getExpiresTime()));
            String format = getString(R.string.weibosdk_demo_token_to_string_format_1);
            mUserInfoView.setText(String.format(format, mAccessToken.getToken(), date));
        }
        
        // 注销按钮
        mUserInfoButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAccessToken != null && mAccessToken.isSessionValid()) {
                    //new UserInfoAPI(mAccessToken).getUserInfo(mRequestListener);
                    new userInfoTask().execute();
                } else {
                    mUserInfoView.setText(R.string.weibosdk_demo_access_token_is_empty);
                }
            }
        });
    }
    
    class userInfoTask extends AsyncTask<Integer, Integer, String>{
    	UserInfoAPI userInfoAPI;
    	@Override
		protected void onPreExecute() {
    		userInfoAPI = new UserInfoAPI(mAccessToken);
			super.onPreExecute();
		}

		@Override 
		protected String doInBackground(Integer... params) {
    		String resp = userInfoAPI.getUserInfoSync();
    		return resp;
		}

		@Override
		protected void onPostExecute(String result) {
			mUserInfoView.setText(result);
			super.onPostExecute(result);
		}
    }
    /**
     * 注销按钮的监听器，接收处理结果。（API请求结果的监听器）
     */
    private class UserInfoRequestListener implements RequestListener {
        @Override
        public void onComplete(String response) {
            if (!TextUtils.isEmpty(response)) {
                try {
                       
                	mUserInfoView.setText(response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        
        @Override
        public void onComplete4binary(ByteArrayOutputStream responseOS) {
            // Do nothing
        } 
        
        @Override
        public void onIOException(IOException e) {
            mUserInfoView.setText(R.string.weibosdk_demo_userinfo_failed);
        }

        @Override
        public void onError(WeiboException e) {
            mUserInfoView.setText(R.string.weibosdk_demo_userinfo_failed);
        }
    }
}
